<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.9.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
  <link href="/blog/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">







<link href="/blog/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/blog/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/blog/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/blog/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/blog/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/blog/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Spring IOC,">










<meta name="description" content="本文讲解Spring IOC的知识，包括：IOC的What、Why、How；Spring IOC工作机制；Spring IOC实例化Bean、注入Bean属性、Bean的作用域视频课程地址：https://www.imooc.com/learn/1108">
<meta name="keywords" content="Spring IOC">
<meta property="og:type" content="article">
<meta property="og:title" content="Spring IOC一">
<meta property="og:url" content="https://aiolos123.gitee.io/blog/2019/11/09/what-is-spring-IOC-1/index.html">
<meta property="og:site_name" content="Aiolos">
<meta property="og:description" content="本文讲解Spring IOC的知识，包括：IOC的What、Why、How；Spring IOC工作机制；Spring IOC实例化Bean、注入Bean属性、Bean的作用域视频课程地址：https://www.imooc.com/learn/1108">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191111175107938.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191111175214735.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191111175449577.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191111175520591.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191112082935865.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191112091014027.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191112091227618.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191112093455282.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191112104321885.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191112104415007.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191112114527272.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191112114527272.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191112121446320.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191112171928712.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191112172330790.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191112173103277.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191112173327512.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191112173735493.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191112174440580.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191112175552626.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191112175057006.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191113093201400.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191113095816743.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191113100633764.jpg">
<meta property="og:updated_time" content="2019-11-13T02:17:29.391Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Spring IOC一">
<meta name="twitter:description" content="本文讲解Spring IOC的知识，包括：IOC的What、Why、How；Spring IOC工作机制；Spring IOC实例化Bean、注入Bean属性、Bean的作用域视频课程地址：https://www.imooc.com/learn/1108">
<meta name="twitter:image" content="https://aiolos123.gitee.io/blog/images/20191111175107938.jpg">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/blog/',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://aiolos123.gitee.io/blog/2019/11/09/what-is-spring-IOC-1/">





  <title>Spring IOC一 | Aiolos</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/blog/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Aiolos</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">记录我的成长点滴</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/blog/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/blog/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/blog/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br>
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/blog/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            归档
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://aiolos123.gitee.io/blog/blog/2019/11/09/what-is-spring-IOC-1/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="aiolos">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/blog/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Aiolos">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">Spring IOC一</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2019-11-09T10:59:13+08:00">
                2019-11-09
              </time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blog/categories/Java基础/" itemprop="url" rel="index">
                    <span itemprop="name">Java基础</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>本文讲解Spring IOC的知识，包括：IOC的What、Why、How；Spring IOC工作机制；Spring IOC实例化Bean、注入Bean属性、Bean的作用域<br>视频课程地址：<a href="https://www.imooc.com/learn/1108" target="_blank" rel="noopener">https://www.imooc.com/learn/1108</a></p>
<a id="more"></a>

<h2 id="JavaWeb发展史"><a href="#JavaWeb发展史" class="headerlink" title="JavaWeb发展史"></a>JavaWeb发展史</h2><ol>
<li><del>JavaBean+Servlet+JSP</del></li>
<li><del>EJB</del></li>
<li>SSM</li>
<li>SpringBoot</li>
<li>Dubbo微服务</li>
<li>SpringCloud微服务</li>
<li>SpringCloud Alibaba微服务</li>
</ol>
<h2 id="课程介绍"><a href="#课程介绍" class="headerlink" title="课程介绍"></a>课程介绍</h2><h3 id="课程内容"><a href="#课程内容" class="headerlink" title="课程内容"></a>课程内容</h3><ol>
<li>介绍IOC并编写一个简单的IOC容器</li>
<li>介绍如何通过xml的方式完成SpringIoc对Bean的管理</li>
<li>介绍如何通过SpringIOC注解完成对Bean的生命周期管理</li>
</ol>
<h3 id="课程目标"><a href="#课程目标" class="headerlink" title="课程目标"></a>课程目标</h3><ol>
<li>理解Ioc的概念及存在的意义</li>
<li>学会使用SpringIoc阿里完成对Bean生命周期的管理(两种方式：xml和注解)</li>
</ol>
<h2 id="什么是IOC"><a href="#什么是IOC" class="headerlink" title="什么是IOC"></a>什么是IOC</h2><blockquote>
<p>IOC: Inversion Of Control(控制反转)、 依赖注入(DI)</p>
</blockquote>
<ol>
<li>控制什么?<br> <strong>控制Java Bean对象的创建及销毁，及控制Java Bean对象的整个生命周期</strong></li>
<li>反转什么?<br> <strong>将对象的控制权交给Ioc容器</strong></li>
</ol>
<blockquote>
<p>反转之前是谁创建Bean，谁控制Bean；反转之后，Bean对象的控制权都统一交给IOC容器</p>
</blockquote>
<h2 id="为什么要有IOC"><a href="#为什么要有IOC" class="headerlink" title="为什么要有IOC"></a>为什么要有IOC</h2><h3 id="没有IOC的日子"><a href="#没有IOC的日子" class="headerlink" title="没有IOC的日子"></a>没有IOC的日子</h3><ol>
<li><p>什么是依赖———— ZhangSan对象依赖Audi对象，因为ZhangSan对象依赖Audi对象完成自己的业务<br><img src="/blog/images/20191111175107938.jpg" alt="什么是依赖"></p>
</li>
<li><p>多个业务就得创建多个方法<br><img src="/blog/images/20191111175214735.jpg" alt="多件事就得多个方法"></p>
</li>
<li><p>上述代码存在的问题————高耦合</p>
<blockquote>
<p>张三所有的行为都需要自己主动创建并销毁一辆车；更换车辆的代价是巨大的</p>
</blockquote>
</li>
<li><p>改进一下————改为成员变量<br><img src="/blog/images/20191111175449577.jpg" alt="改进一下"></p>
</li>
<li><p>但依然有问题：<br><img src="/blog/images/20191111175520591.jpg" alt="但依然有问题"></p>
</li>
<li><p>由谁来创建车辆? ————IOC容器<br><img src="/blog/images/20191112082935865.jpg" alt="由谁来创建车辆"></p>
</li>
</ol>
<h2 id="Ioc是如何工作的"><a href="#Ioc是如何工作的" class="headerlink" title="Ioc是如何工作的"></a>Ioc是如何工作的</h2><h3 id="实现一个自己的Ioc容器————利用反射"><a href="#实现一个自己的Ioc容器————利用反射" class="headerlink" title="实现一个自己的Ioc容器————利用反射"></a>实现一个自己的Ioc容器————利用反射</h3><blockquote>
<p>约定1：所有Bean的生命周期交由Ioc容器管理<br>约定2：所有被依赖的Bean通过构造方法执行注入<br>约定3：被依赖的Bean需要优先创建</p>
</blockquote>
<ol>
<li><p>业务的类图如下：<br><img src="/blog/images/20191112091014027.jpg" alt="业务的类图如下"></p>
</li>
<li><p>自定义的IOC容器的代码如下：</p>
<figure class="highlight dart"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"><span class="markdown">/**</span></span></span><br><span class="line"><span class="comment"><span class="markdown"><span class="bullet"> * </span>自定义IOC容器的功能</span></span></span><br><span class="line"><span class="comment"><span class="markdown"><span class="bullet"> * </span>1、实例化Bean</span></span></span><br><span class="line"><span class="comment"><span class="markdown"><span class="bullet"> * </span>2、保存Bean</span></span></span><br><span class="line"><span class="comment"><span class="markdown"><span class="bullet"> * </span>3、提供Bean</span></span></span><br><span class="line"><span class="comment"><span class="markdown"><span class="bullet"> * </span>4、每一个Bean要产生一个唯一的id与之对应</span></span></span><br><span class="line"><span class="comment"><span class="markdown"> */</span></span></span><br><span class="line">public <span class="class"><span class="keyword">class</span> <span class="title">MyIocContainer</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//2、保存Bean。出于线程安全考虑，使用ConcurrentHashMap</span></span><br><span class="line">    private <span class="built_in">Map</span>&lt;<span class="built_in">String</span>,<span class="built_in">Object</span>&gt; beans = <span class="keyword">new</span> ConcurrentHashMap&lt;&gt;();</span><br><span class="line"></span><br><span class="line">    <span class="comment"><span class="markdown">/**</span></span></span><br><span class="line"><span class="comment"><span class="markdown"><span class="bullet">     * </span>1、实例化Bean。</span></span></span><br><span class="line"><span class="comment"><span class="markdown"><span class="bullet">     * </span>作用：委托Ioc容器创建一个bean</span></span></span><br><span class="line"><span class="comment"><span class="markdown"><span class="bullet">     * </span>@param clazz  要创建的bean的class</span></span></span><br><span class="line"><span class="comment"><span class="markdown"><span class="bullet">     * </span>@param beanId BeanId</span></span></span><br><span class="line"><span class="comment"><span class="markdown"><span class="bullet">     * </span>@param paramBeanIds 要创建的bean的class的构造方法所需要的参数的beanId们</span></span></span><br><span class="line"><span class="comment"><span class="markdown"><span class="code">     */</span></span></span></span><br><span class="line">    public <span class="keyword">void</span> setBeans(Class&lt;?&gt; clazz, <span class="built_in">String</span> beanId,<span class="built_in">String</span>... paramBeanIds)&#123;</span><br><span class="line">        <span class="comment">//1. 组装构造方法所需的参数值</span></span><br><span class="line">        <span class="built_in">Object</span>[] paramValues = <span class="keyword">new</span> <span class="built_in">Object</span>[paramBeanIds.length];</span><br><span class="line">        <span class="keyword">for</span> (<span class="built_in">int</span> i = <span class="number">0</span>; i &lt; paramBeanIds.length; i++) &#123;</span><br><span class="line">            <span class="comment">//约定3：被依赖的Bean需要优先创建</span></span><br><span class="line">            paramValues[i] = beans.<span class="keyword">get</span>(paramBeanIds[i]);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">//2. 调用构造方法实例化bean</span></span><br><span class="line">        <span class="built_in">Object</span> bean = <span class="keyword">null</span>;</span><br><span class="line">        <span class="keyword">for</span> (Constructor&lt;?&gt; constructor : clazz.getConstructors())&#123;</span><br><span class="line">            <span class="keyword">try</span> &#123;</span><br><span class="line">                bean = constructor.newInstance(paramValues);</span><br><span class="line">                <span class="comment">//不处理所有异常，如果没有实例化则bean一定为null</span></span><br><span class="line">            &#125; <span class="keyword">catch</span> (InstantiationException e) &#123;</span><br><span class="line">            &#125; <span class="keyword">catch</span> (IllegalAccessException e) &#123;</span><br><span class="line">            &#125; <span class="keyword">catch</span> (InvocationTargetException e) &#123;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">if</span>(bean == <span class="keyword">null</span>)&#123;</span><br><span class="line">            <span class="comment">//实例化失败，强制报错</span></span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> RuntimeException(<span class="string">"找不到合适的构造方法实例化bean"</span>);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">//3. 将实例化的bean放入beans</span></span><br><span class="line">        beans.put(beanId, bean);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment"><span class="markdown">/**</span></span></span><br><span class="line"><span class="comment"><span class="markdown"><span class="bullet">     * </span>3、提供Bean。因为每一个Bean要产生一个唯一的id与之对应，所以通过beanId获取Bean</span></span></span><br><span class="line"><span class="comment"><span class="markdown"><span class="bullet">     * </span>作用：根据beanId获取一个bean</span></span></span><br><span class="line"><span class="comment"><span class="markdown"><span class="bullet">     * </span>@param beanId</span></span></span><br><span class="line"><span class="comment"><span class="markdown"><span class="bullet">     * </span>@return 返回bean</span></span></span><br><span class="line"><span class="comment"><span class="markdown"><span class="code">     */</span></span></span></span><br><span class="line">    public <span class="built_in">Object</span> getBean(<span class="built_in">String</span> beanId)&#123;</span><br><span class="line">        <span class="keyword">return</span> beans.<span class="keyword">get</span>(beanId);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
<li><p>使用Ioc容器执行结果如下图：<br><img src="/blog/images/20191112091227618.jpg" alt="使用Ioc容器执行结果"></p>
</li>
<li><p>使用Ioc容器的好处：</p>
<blockquote>
<ol>
<li>所有的依赖关系都被集中统一管理起来，清晰明了(见before方法)</li>
<li>每个类只需要关注于自己的业务逻辑(见ZhangSan、LiSi类——无需实例化Car，直接得到Car的实例化对象)</li>
<li>修改依赖关系变得很容易了(在before方法中修改即可)</li>
</ol>
</blockquote>
</li>
</ol>
<h3 id="使用SpringIoc容器管理Bean"><a href="#使用SpringIoc容器管理Bean" class="headerlink" title="使用SpringIoc容器管理Bean"></a>使用SpringIoc容器管理Bean</h3><ol>
<li><p>创建Bean类</p>
<figure class="highlight cs"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title">Bean</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">Bean</span>(<span class="params"></span>)</span> &#123;</span><br><span class="line">        System.<span class="keyword">out</span>.println(<span class="string">"Bean 被创建了..."</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
<li><p>引入Spring依赖</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.springframework<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>spring-core<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">version</span>&gt;</span>4.3.20.RELEASE<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.springframework<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>spring-context<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">version</span>&gt;</span>4.3.20.RELEASE<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br></pre></td></tr></table></figure>
</li>
<li><p>创建Spring配置文件</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&lt;?xml version="1.0" encoding="UTF-8" ?&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">beans</span> <span class="attr">xmlns</span>=<span class="string">"http://www.springframework.org/schema/beans"</span></span></span><br><span class="line"><span class="tag">       <span class="attr">xmlns:xsi</span>=<span class="string">"http://www.w3.org/2001/XMLSchema-instance"</span></span></span><br><span class="line"><span class="tag">       <span class="attr">xsi:schemaLocation</span>=<span class="string">"http://www.springframework.org/schema/beans</span></span></span><br><span class="line"><span class="tag"><span class="string">                  http://www.springframework.org/schema/beans/spring-beans.xsd"</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">&lt;!--将一个Bean交由Spring IOC创建并管理--&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">"bean"</span> <span class="attr">class</span>=<span class="string">"com.aiolos.springioc.Bean"</span> /&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">beans</span>&gt;</span></span><br></pre></td></tr></table></figure>
</li>
<li><p>使用Bean</p>
<figure class="highlight cs"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title">IocTest</span> &#123;</span><br><span class="line"></span><br><span class="line">    @Test</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">test</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">        <span class="comment">//创建Spring上下文</span></span><br><span class="line">        ApplicationContext applicationContext = <span class="keyword">new</span> ClassPathXmlApplicationContext(<span class="string">"spring.xml"</span>);</span><br><span class="line">        <span class="comment">//通过Spring上下文获取Bean实例</span></span><br><span class="line">        Bean bean = applicationContext.getBean(<span class="string">"bean"</span>, Bean.class);</span><br><span class="line">        System.<span class="keyword">out</span>.println(bean);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

</li>
</ol>
<p>运行结果如下图：<br><img src="/blog/images/20191112093455282.jpg" alt="使用Ioc容器执行结果"></p>
<h3 id="总结：使用SpringIOC管理Bean的三个步骤"><a href="#总结：使用SpringIOC管理Bean的三个步骤" class="headerlink" title="总结：使用SpringIOC管理Bean的三个步骤"></a>总结：使用SpringIOC管理Bean的三个步骤</h3><ol>
<li>在xml中声明Bean</li>
<li>使用xml文件来创建Spring上下文</li>
<li>通过Spring上下文获取Bean实例</li>
</ol>
<h2 id="使用Spring-IOC实例化Bean的三种方式"><a href="#使用Spring-IOC实例化Bean的三种方式" class="headerlink" title="使用Spring IOC实例化Bean的三种方式"></a>使用Spring IOC实例化Bean的三种方式</h2><h3 id="通过默认构造方法实例化Bean"><a href="#通过默认构造方法实例化Bean" class="headerlink" title="通过默认构造方法实例化Bean"></a>通过默认构造方法实例化Bean</h3><blockquote>
<p>同上一节《使用SpringIoc容器管理Bean》的代码</p>
</blockquote>
<h3 id="通过静态工厂方法实例化Bean"><a href="#通过静态工厂方法实例化Bean" class="headerlink" title="通过静态工厂方法实例化Bean"></a>通过静态工厂方法实例化Bean</h3><ol>
<li><p>创建BeanFactory</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Bean2Factory</span> &#123;</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">//静态工厂方法</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> Bean2 <span class="title">getBean2</span><span class="params">()</span></span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> Bean2();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
<li><p>在xml中配置</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&lt;?xml version="1.0" encoding="UTF-8" ?&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">beans</span> <span class="attr">xmlns</span>=<span class="string">"http://www.springframework.org/schema/beans"</span></span></span><br><span class="line"><span class="tag">       <span class="attr">xmlns:xsi</span>=<span class="string">"http://www.w3.org/2001/XMLSchema-instance"</span></span></span><br><span class="line"><span class="tag">       <span class="attr">xsi:schemaLocation</span>=<span class="string">"http://www.springframework.org/schema/beans</span></span></span><br><span class="line"><span class="tag"><span class="string">                  http://www.springframework.org/schema/beans/spring-beans.xsd"</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">&lt;!--通过BeanFactory将一个Bean交由Spring IOC创建并管理管理--&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">bean</span> <span class="attr">class</span>=<span class="string">"com.aiolos.springioc.Bean2Factory"</span></span></span><br><span class="line"><span class="tag">          <span class="attr">factory-method</span>=<span class="string">"getBean2"</span> <span class="attr">id</span>=<span class="string">"bean2"</span> /&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;/<span class="name">beans</span>&gt;</span></span><br></pre></td></tr></table></figure>
</li>
<li><p>使用Bean</p>
<figure class="highlight cs"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title">IocTest</span> &#123;</span><br><span class="line"></span><br><span class="line">    @Test</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">test</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">        <span class="comment">//创建Spring上下文</span></span><br><span class="line">        ApplicationContext applicationContext = <span class="keyword">new</span> ClassPathXmlApplicationContext(<span class="string">"spring.xml"</span>);</span><br><span class="line">        </span><br><span class="line">        <span class="comment">//直接获取Bean2的方式——无需xml配置</span></span><br><span class="line">        <span class="comment">//Bean2 bean2 = Bean2Factory.getBean2();</span></span><br><span class="line">        <span class="comment">//通过上下文获取Bean2实例的方式——需要xml配置</span></span><br><span class="line">        Bean2 bean2 = applicationContext.getBean(<span class="string">"bean2"</span>, Bean2.class);</span><br><span class="line">        System.<span class="keyword">out</span>.println(bean2);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

</li>
</ol>
<h3 id="通过实例工厂方法实例化Bean"><a href="#通过实例工厂方法实例化Bean" class="headerlink" title="通过实例工厂方法实例化Bean"></a>通过实例工厂方法实例化Bean</h3><ol>
<li><p>创建BeanFactory</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Bean3Factory</span> &#123;</span></span><br><span class="line">    <span class="comment">//实例工厂方法</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Bean3 <span class="title">getBean3</span><span class="params">()</span></span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> Bean3();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
<li><p>在xml中配置</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&lt;?xml version="1.0" encoding="UTF-8" ?&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">beans</span> <span class="attr">xmlns</span>=<span class="string">"http://www.springframework.org/schema/beans"</span></span></span><br><span class="line"><span class="tag">       <span class="attr">xmlns:xsi</span>=<span class="string">"http://www.w3.org/2001/XMLSchema-instance"</span></span></span><br><span class="line"><span class="tag">       <span class="attr">xsi:schemaLocation</span>=<span class="string">"http://www.springframework.org/schema/beans</span></span></span><br><span class="line"><span class="tag"><span class="string"></span></span></span><br><span class="line"><span class="tag"><span class="string">    &lt;!--通过实例方法将一个Bean交由Spring IOC创建并管理管理--&gt;</span></span></span><br><span class="line"><span class="tag"><span class="string">    &lt;bean class="</span><span class="attr">com.aiolos.springioc.Bean3Factory</span>" <span class="attr">id</span>=<span class="string">"bean3Factory"</span> /&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">bean</span> <span class="attr">class</span>=<span class="string">"com.aiolos.springioc.Bean3Factory"</span> <span class="attr">factory-bean</span>=<span class="string">"bean3Factory"</span></span></span><br><span class="line"><span class="tag">          <span class="attr">factory-method</span>=<span class="string">"getBean3"</span> <span class="attr">id</span>=<span class="string">"bean2"</span> /&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;/<span class="name">beans</span>&gt;</span></span><br></pre></td></tr></table></figure>
</li>
<li><p>使用Bean</p>
<figure class="highlight cs"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title">IocTest</span> &#123;</span><br><span class="line"></span><br><span class="line">    @Test</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">test</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">        <span class="comment">//创建Spring上下文</span></span><br><span class="line">        ApplicationContext applicationContext = <span class="keyword">new</span> ClassPathXmlApplicationContext(<span class="string">"spring.xml"</span>);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//直接获取Bean3的方式——无需xml配置</span></span><br><span class="line">        <span class="comment">//Bean3Factory bean3Factory = new Bean3Factory();</span></span><br><span class="line">        <span class="comment">//Bean3 bean3 = bean3Factory.getBean3();</span></span><br><span class="line">        <span class="comment">//通过上下文获取Bean3实例的方式——需要xml配置</span></span><br><span class="line">        Bean3 bean3 = applicationContext.getBean(<span class="string">"bean3"</span>, Bean3.class);</span><br><span class="line">        System.<span class="keyword">out</span>.println(bean3);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

</li>
</ol>
<h3 id="为Bean对象起别名的两种方式"><a href="#为Bean对象起别名的两种方式" class="headerlink" title="为Bean对象起别名的两种方式"></a>为Bean对象起别名的两种方式</h3><p><img src="/blog/images/20191112104321885.jpg" alt="Bean的别名的两种方式"></p>
<h3 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h3><p><img src="/blog/images/20191112104415007.jpg" alt="Bean的别名的两种方式"></p>
<h2 id="通过Spring-IOC注入Bean的属性值二种方法"><a href="#通过Spring-IOC注入Bean的属性值二种方法" class="headerlink" title="通过Spring IOC注入Bean的属性值二种方法"></a>通过Spring IOC注入Bean的属性值二种方法</h2><h3 id="通过构造方法注入Bean的属性值"><a href="#通过构造方法注入Bean的属性值" class="headerlink" title="通过构造方法注入Bean的属性值"></a>通过构造方法注入Bean的属性值</h3><ol>
<li><p>创建有属性的Bean</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Bean</span> &#123;</span></span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> AnotherBean anotherBean;</span><br><span class="line">    <span class="keyword">private</span> String <span class="built_in">string</span>;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">Bean</span><span class="params">(AnotherBean anotherBean, String <span class="built_in">string</span>)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.anotherBean = anotherBean;</span><br><span class="line">        <span class="keyword">this</span>.<span class="built_in">string</span> = <span class="built_in">string</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//getter和setter</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
<li><p>在xml中配置</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&lt;?xml version="1.0" encoding="UTF-8" ?&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">beans</span> <span class="attr">xmlns</span>=<span class="string">"http://www.springframework.org/schema/beans"</span></span></span><br><span class="line"><span class="tag">       <span class="attr">xmlns:xsi</span>=<span class="string">"http://www.w3.org/2001/XMLSchema-instance"</span></span></span><br><span class="line"><span class="tag">       <span class="attr">xsi:schemaLocation</span>=<span class="string">"http://www.springframework.org/schema/beans</span></span></span><br><span class="line"><span class="tag"><span class="string">                  http://www.springframework.org/schema/beans/spring-beans.xsd"</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">&lt;!--通过构造方法实例化Bean并注入属性值--&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">bean</span> <span class="attr">class</span>=<span class="string">"com.aiolos.spring03.AnotherBean"</span> <span class="attr">id</span>=<span class="string">"anotherBean"</span> /&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">bean</span> <span class="attr">class</span>=<span class="string">"com.aiolos.spring03.Bean"</span> &gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">constructor-arg</span> <span class="attr">index</span>=<span class="string">"0"</span> <span class="attr">name</span>=<span class="string">"anotherBean"</span></span></span><br><span class="line"><span class="tag">            <span class="attr">type</span>=<span class="string">"com.aiolos.spring03.AnotherBean"</span></span></span><br><span class="line"><span class="tag">            <span class="attr">ref</span>=<span class="string">"anotherBean"</span>/&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">constructor-arg</span> <span class="attr">index</span>=<span class="string">"1"</span> <span class="attr">name</span>=<span class="string">"string"</span></span></span><br><span class="line"><span class="tag">                         <span class="attr">type</span>=<span class="string">"java.lang.String"</span> <span class="attr">value</span>=<span class="string">"aaa"</span>/&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">bean</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;/<span class="name">beans</span>&gt;</span></span><br></pre></td></tr></table></figure>

</li>
</ol>
<p><strong>注意：constructor-arg标签中的index、name、type的选择原则：选择能唯一标识出参数即可，如index、name</strong></p>
<ol start="3">
<li>获取Bean实例<br><img src="/blog/images/20191112114527272.jpg" alt="获取Bean实例"></li>
</ol>
<h3 id="通过set方法注入Bean的属性值"><a href="#通过set方法注入Bean的属性值" class="headerlink" title="通过set方法注入Bean的属性值"></a>通过set方法注入Bean的属性值</h3><ol>
<li><p>创建有属性的Bean</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Bean</span> &#123;</span></span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> AnotherBean anotherBean;</span><br><span class="line">    <span class="keyword">private</span> String <span class="built_in">string</span>;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> AnotherBean anotherBean1;</span><br><span class="line">    <span class="keyword">private</span> String string1;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">Bean</span><span class="params">(AnotherBean anotherBean, String <span class="built_in">string</span>)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.anotherBean = anotherBean;</span><br><span class="line">        <span class="keyword">this</span>.<span class="built_in">string</span> = <span class="built_in">string</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//getter和setter</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
<li><p>在xml中配置</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&lt;?xml version="1.0" encoding="UTF-8" ?&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">beans</span> <span class="attr">xmlns</span>=<span class="string">"http://www.springframework.org/schema/beans"</span></span></span><br><span class="line"><span class="tag">       <span class="attr">xmlns:xsi</span>=<span class="string">"http://www.w3.org/2001/XMLSchema-instance"</span></span></span><br><span class="line"><span class="tag">       <span class="attr">xsi:schemaLocation</span>=<span class="string">"http://www.springframework.org/schema/beans</span></span></span><br><span class="line"><span class="tag"><span class="string">                  http://www.springframework.org/schema/beans/spring-beans.xsd"</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">&lt;!--注入Bean的属性值--&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">bean</span> <span class="attr">class</span>=<span class="string">"com.aiolos.spring03.AnotherBean"</span> <span class="attr">id</span>=<span class="string">"anotherBean"</span> /&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">bean</span> <span class="attr">class</span>=<span class="string">"com.aiolos.spring03.Bean"</span> <span class="attr">id</span>=<span class="string">"bean4"</span>&gt;</span></span><br><span class="line">        <span class="comment">&lt;!--通过构造方法注入Bean的属性值--&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">constructor-arg</span> <span class="attr">index</span>=<span class="string">"0"</span> <span class="attr">name</span>=<span class="string">"anotherBean"</span></span></span><br><span class="line"><span class="tag">                         <span class="attr">type</span>=<span class="string">"com.aiolos.spring03.AnotherBean"</span></span></span><br><span class="line"><span class="tag">                         <span class="attr">ref</span>=<span class="string">"anotherBean"</span> /&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">constructor-arg</span> <span class="attr">index</span>=<span class="string">"1"</span> <span class="attr">name</span>=<span class="string">"string"</span></span></span><br><span class="line"><span class="tag">                         <span class="attr">type</span>=<span class="string">"java.lang.String"</span></span></span><br><span class="line"><span class="tag">                         <span class="attr">value</span>=<span class="string">"aaaa"</span> /&gt;</span></span><br><span class="line"></span><br><span class="line">        <span class="comment">&lt;!--通过set方法注入Bean的属性值： name为属性值--&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"anotherBean1"</span> <span class="attr">ref</span>=<span class="string">"anotherBean"</span> /&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"string1"</span> <span class="attr">value</span>=<span class="string">"bbbb"</span> /&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">bean</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;/<span class="name">beans</span>&gt;</span></span><br></pre></td></tr></table></figure>
</li>
<li><p>获取Bean实例<br><img src="/blog/images/20191112114527272.jpg" alt="获取Bean实例"></p>
</li>
</ol>
<h4 id="集合类型的属性值的注入"><a href="#集合类型的属性值的注入" class="headerlink" title="集合类型的属性值的注入"></a>集合类型的属性值的注入</h4><ol>
<li><p>Bean类</p>
<figure class="highlight lasso"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">private</span> <span class="built_in">List</span>&lt;<span class="built_in">String</span>&gt; stringList;</span><br><span class="line"><span class="keyword">private</span> <span class="built_in">List</span>&lt;AnotherBean&gt; anotherBeanList;</span><br><span class="line"></span><br><span class="line"><span class="keyword">private</span> <span class="built_in">Map</span>&lt;<span class="built_in">String</span>, <span class="built_in">String</span>&gt; stringMap;</span><br><span class="line"><span class="keyword">private</span> <span class="built_in">Map</span>&lt;AnotherBean, AnotherBean&gt; anotherBeanMap;</span><br><span class="line"></span><br><span class="line"><span class="keyword">private</span> <span class="built_in">Set</span>&lt;<span class="built_in">String</span>&gt; stringSet;</span><br><span class="line"><span class="keyword">private</span> <span class="built_in">Set</span>&lt;AnotherBean&gt; anotherBeanSet;</span><br><span class="line"></span><br><span class="line"><span class="keyword">private</span> Properties properties;</span><br></pre></td></tr></table></figure>
</li>
<li><p>xml配置</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">&lt;!--注入Bean的属性值--&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">bean</span> <span class="attr">class</span>=<span class="string">"com.aiolos.spring03.AnotherBean"</span> <span class="attr">id</span>=<span class="string">"anotherBean"</span> /&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">bean</span> <span class="attr">class</span>=<span class="string">"com.aiolos.spring03.AnotherBean"</span> <span class="attr">id</span>=<span class="string">"anotherBean1"</span> /&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">bean</span> <span class="attr">class</span>=<span class="string">"com.aiolos.spring03.Bean"</span> <span class="attr">id</span>=<span class="string">"bean4"</span>&gt;</span></span><br><span class="line">        <span class="comment">&lt;!--通过构造方法注入Bean的属性值--&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">constructor-arg</span> <span class="attr">index</span>=<span class="string">"0"</span> <span class="attr">name</span>=<span class="string">"anotherBean"</span></span></span><br><span class="line"><span class="tag">                         <span class="attr">type</span>=<span class="string">"com.aiolos.spring03.AnotherBean"</span></span></span><br><span class="line"><span class="tag">                         <span class="attr">ref</span>=<span class="string">"anotherBean"</span> /&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">constructor-arg</span> <span class="attr">index</span>=<span class="string">"1"</span> <span class="attr">name</span>=<span class="string">"string"</span></span></span><br><span class="line"><span class="tag">                         <span class="attr">type</span>=<span class="string">"java.lang.String"</span></span></span><br><span class="line"><span class="tag">                         <span class="attr">value</span>=<span class="string">"aaaa"</span> /&gt;</span></span><br><span class="line"></span><br><span class="line">        <span class="comment">&lt;!--通过set方法注入Bean的属性值--&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"anotherBean1"</span> <span class="attr">ref</span>=<span class="string">"anotherBean"</span> /&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"string1"</span> <span class="attr">value</span>=<span class="string">"bbbb"</span> /&gt;</span></span><br><span class="line"></span><br><span class="line">        <span class="comment">&lt;!--注入Bean的集合类型的属性值--&gt;</span></span><br><span class="line">        <span class="comment">&lt;!--List--&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"stringList"</span> &gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">list</span>&gt;</span></span><br><span class="line">                <span class="tag">&lt;<span class="name">value</span>&gt;</span>aaaaa<span class="tag">&lt;/<span class="name">value</span>&gt;</span></span><br><span class="line">                <span class="tag">&lt;<span class="name">value</span>&gt;</span>bbbbb<span class="tag">&lt;/<span class="name">value</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;/<span class="name">list</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;/<span class="name">property</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"anotherBeanList"</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">list</span>&gt;</span></span><br><span class="line">                <span class="tag">&lt;<span class="name">ref</span> <span class="attr">bean</span>=<span class="string">"anotherBean"</span> /&gt;</span></span><br><span class="line">                <span class="tag">&lt;<span class="name">ref</span> <span class="attr">bean</span>=<span class="string">"anotherBean1"</span> /&gt;</span></span><br><span class="line">            <span class="tag">&lt;/<span class="name">list</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;/<span class="name">property</span>&gt;</span></span><br><span class="line">        <span class="comment">&lt;!--Set--&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"stringSet"</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">set</span>&gt;</span></span><br><span class="line">                <span class="tag">&lt;<span class="name">value</span>&gt;</span>aaaaa<span class="tag">&lt;/<span class="name">value</span>&gt;</span></span><br><span class="line">                <span class="tag">&lt;<span class="name">value</span>&gt;</span>bbbbb<span class="tag">&lt;/<span class="name">value</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;/<span class="name">set</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;/<span class="name">property</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"anotherBeanSet"</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">set</span>&gt;</span></span><br><span class="line">                <span class="tag">&lt;<span class="name">ref</span> <span class="attr">bean</span>=<span class="string">"anotherBean"</span> /&gt;</span></span><br><span class="line">                <span class="tag">&lt;<span class="name">ref</span> <span class="attr">bean</span>=<span class="string">"anotherBean1"</span> /&gt;</span></span><br><span class="line">            <span class="tag">&lt;/<span class="name">set</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;/<span class="name">property</span>&gt;</span></span><br><span class="line">        <span class="comment">&lt;!--Map--&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"stringMap"</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">map</span>&gt;</span></span><br><span class="line">                <span class="tag">&lt;<span class="name">entry</span> <span class="attr">key</span>=<span class="string">"ccccc"</span> <span class="attr">value</span>=<span class="string">"ddddd"</span> /&gt;</span></span><br><span class="line">                <span class="tag">&lt;<span class="name">entry</span> <span class="attr">key</span>=<span class="string">"eeeee"</span> <span class="attr">value</span>=<span class="string">"ffff"</span> /&gt;</span></span><br><span class="line">            <span class="tag">&lt;/<span class="name">map</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;/<span class="name">property</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"anotherBeanMap"</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">map</span>&gt;</span></span><br><span class="line">                <span class="tag">&lt;<span class="name">entry</span> <span class="attr">key-ref</span>=<span class="string">"anotherBean"</span> <span class="attr">value-ref</span>=<span class="string">"anotherBean"</span> /&gt;</span></span><br><span class="line">                <span class="tag">&lt;<span class="name">entry</span> <span class="attr">key-ref</span>=<span class="string">"anotherBean1"</span> <span class="attr">value-ref</span>=<span class="string">"anotherBean1"</span> /&gt;</span></span><br><span class="line">            <span class="tag">&lt;/<span class="name">map</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;/<span class="name">property</span>&gt;</span></span><br><span class="line">        <span class="comment">&lt;!--properties--&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"properties"</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">props</span>&gt;</span></span><br><span class="line">                <span class="tag">&lt;<span class="name">prop</span> <span class="attr">key</span>=<span class="string">"aaaa"</span>&gt;</span>bbbb<span class="tag">&lt;/<span class="name">prop</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;/<span class="name">props</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;/<span class="name">property</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">bean</span>&gt;</span></span><br></pre></td></tr></table></figure>
</li>
<li><p>获取bean实例<br><img src="/blog/images/20191112121446320.jpg" alt="获取Bean实例"></p>
</li>
</ol>
<h4 id="null类型的属性值的注入"><a href="#null类型的属性值的注入" class="headerlink" title="null类型的属性值的注入"></a>null类型的属性值的注入</h4><ol>
<li><p>Bean类</p>
<figure class="highlight actionscript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//注入null值属性</span></span><br><span class="line"><span class="keyword">private</span> AnotherBean anotherBean2;</span><br><span class="line"><span class="comment">//getter和setter方法</span></span><br></pre></td></tr></table></figure>
</li>
<li><p>xml配置</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">&lt;!--注入null值属性--&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"anotherBean2"</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">null</span> /&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">property</span>&gt;</span></span><br></pre></td></tr></table></figure>

</li>
</ol>
<h4 id="注入时创建内部Bean"><a href="#注入时创建内部Bean" class="headerlink" title="注入时创建内部Bean"></a>注入时创建内部Bean</h4><figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">&lt;!--注入时创建内部Bean--&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"anotherBean"</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">bean</span> <span class="attr">class</span>=<span class="string">"com.aiolos.spring03.AnotherBean"</span> /&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">property</span>&gt;</span></span><br></pre></td></tr></table></figure>

<h3 id="构造方法和set方法注入属性值的简写形式——修改配置文件即可"><a href="#构造方法和set方法注入属性值的简写形式——修改配置文件即可" class="headerlink" title="构造方法和set方法注入属性值的简写形式——修改配置文件即可"></a>构造方法和set方法注入属性值的简写形式——修改配置文件即可</h3><figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&lt;?xml version="1.0" encoding="UTF-8" ?&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">beans</span> <span class="attr">xmlns</span>=<span class="string">"http://www.springframework.org/schema/beans"</span></span></span><br><span class="line"><span class="tag">       <span class="attr">xmlns:xsi</span>=<span class="string">"http://www.w3.org/2001/XMLSchema-instance"</span></span></span><br><span class="line"><span class="tag">       <span class="attr">xmlns:c</span>=<span class="string">"http://www.springframework.org/schema/c"</span></span></span><br><span class="line"><span class="tag">       <span class="attr">xmlns:p</span>=<span class="string">"http://www.springframework.org/schema/p"</span></span></span><br><span class="line"><span class="tag">       <span class="attr">xsi:schemaLocation</span>=<span class="string">"http://www.springframework.org/schema/beans</span></span></span><br><span class="line"><span class="tag"><span class="string">                  http://www.springframework.org/schema/beans/spring-beans.xsd"</span>&gt;</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="comment">&lt;!--注入Bean的属性值的简写形式</span></span><br><span class="line"><span class="comment">        c: 标签表示构造方法</span></span><br><span class="line"><span class="comment">        p: 标签表示setter方法</span></span><br><span class="line"><span class="comment">    --&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">bean</span> <span class="attr">class</span>=<span class="string">"com.aiolos.spring03.AnotherBean"</span> <span class="attr">id</span>=<span class="string">"anotherBean"</span> /&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">bean</span> <span class="attr">class</span>=<span class="string">"com.aiolos.spring03.Bean"</span> <span class="attr">id</span>=<span class="string">"bean4"</span></span></span><br><span class="line"><span class="tag">          <span class="attr">c:anotherBean-ref</span>=<span class="string">"anotherBean"</span></span></span><br><span class="line"><span class="tag">          <span class="attr">c:string</span>=<span class="string">"aaaaa"</span></span></span><br><span class="line"><span class="tag">          <span class="attr">p:anotherBean1-ref</span>=<span class="string">"anotherBean"</span></span></span><br><span class="line"><span class="tag">          <span class="attr">p:string</span>=<span class="string">"bbbbb"</span></span></span><br><span class="line"><span class="tag">    /&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">beans</span>&gt;</span></span><br></pre></td></tr></table></figure>

<h2 id="Bean的作用域"><a href="#Bean的作用域" class="headerlink" title="Bean的作用域"></a>Bean的作用域</h2><h3 id="Singleton作用域-单例-——-Spring默认就是单例模式"><a href="#Singleton作用域-单例-——-Spring默认就是单例模式" class="headerlink" title="Singleton作用域(单例) —— Spring默认就是单例模式"></a>Singleton作用域(单例) —— Spring默认就是单例模式</h3><ol>
<li>Singleton作用域<blockquote>
<p>一个Spring上下文中，每个Bean只有一个bean实例对象<br>多个Spring上下文中，每个Bean都有多个bean实例对象</p>
</blockquote>
</li>
</ol>
<p><img src="/blog/images/20191112171928712.jpg" alt="Singleton作用域"></p>
<ol start="2">
<li><p>配置Singleton作用域</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">&lt;!--Singleton作用域--&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">bean</span> <span class="attr">class</span>=<span class="string">"com.aiolos.spring04.Bean2"</span> <span class="attr">id</span>=<span class="string">"bean22"</span> <span class="attr">scope</span>=<span class="string">"singleton"</span>/&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">bean</span> <span class="attr">class</span>=<span class="string">"com.aiolos.spring04.Bean"</span> <span class="attr">id</span>=<span class="string">"bean5"</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"bean2"</span> <span class="attr">ref</span>=<span class="string">"bean22"</span> /&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">bean</span>&gt;</span></span><br></pre></td></tr></table></figure>
</li>
<li><p>运行结果<br><img src="/blog/images/20191112172330790.jpg" alt="Singleton作用域"></p>
</li>
<li><p>多个Spring上下文中，就有多个bean实例对象<br><img src="/blog/images/20191112173103277.jpg" alt="Singleton作用域"></p>
</li>
</ol>
<h3 id="prototype作用域-多例"><a href="#prototype作用域-多例" class="headerlink" title="prototype作用域(多例)"></a>prototype作用域(多例)</h3><blockquote>
<p>一个Spring上下文中，每个Bean都有多个bean实例对象<br>每次向Spring上下文请求的Bean实例，都是新的Bean实例</p>
</blockquote>
<p><img src="/blog/images/20191112173327512.jpg" alt="Singleton作用域"></p>
<ol>
<li><p>配置prototype作用域</p>
<figure class="highlight applescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">&lt;bean <span class="built_in">class</span>=<span class="string">"com.aiolos.spring04.Bean2"</span> <span class="built_in">id</span>=<span class="string">"bean22"</span> scope=<span class="string">"prototype"</span>/&gt;</span><br><span class="line">    &lt;bean <span class="built_in">class</span>=<span class="string">"com.aiolos.spring04.Bean"</span> <span class="built_in">id</span>=<span class="string">"bean5"</span>&gt;</span><br><span class="line">        &lt;<span class="keyword">property</span> <span class="built_in">name</span>=<span class="string">"bean2"</span> <span class="keyword">ref</span>=<span class="string">"bean22"</span> /&gt;</span><br><span class="line">    &lt;/bean&gt;</span><br></pre></td></tr></table></figure>
</li>
<li><p>运行结果<br><img src="/blog/images/20191112173735493.jpg" alt="prototype作用域"></p>
</li>
</ol>
<h3 id="单例-多例的组合作用域"><a href="#单例-多例的组合作用域" class="headerlink" title="单例+多例的组合作用域"></a>单例+多例的组合作用域</h3><ol>
<li><p>结论：<br><img src="/blog/images/20191112174440580.jpg" alt="单例+多例的组合作用域"></p>
</li>
<li><p>代码验证：<br><img src="/blog/images/20191112175552626.jpg" alt="单例+多例的组合作用域"></p>
</li>
<li><p>方法注入</p>
<blockquote>
<p>方法注入的应用场景： Bean1是单例，Bean2是多例，Bean1依赖Bean2。希望每次调用Bean1的某方法时，<br>该方法拿到的Bean2都是一个新的实例</p>
</blockquote>
</li>
</ol>
<p>方法注入的实现过程如下图：<br><img src="/blog/images/20191112175057006.jpg" alt="方法注入"></p>
<h3 id="web环境作用域"><a href="#web环境作用域" class="headerlink" title="web环境作用域"></a>web环境作用域</h3><blockquote>
<p>前提： web环境需要配置SpringWeb上下文环境</p>
</blockquote>
<p><img src="/blog/images/20191113093201400.jpg" alt="web环境需要配置SpringWeb上下文环境"></p>
<ol>
<li><p>在pom文件中引入web的依赖，并修改打包方式为war包</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">      <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.springframework<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">      <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>spring-web<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">      <span class="tag">&lt;<span class="name">version</span>&gt;</span>4.3.20.RELEASE<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">      <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.springframework<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">      <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>spring-webmvc<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">      <span class="tag">&lt;<span class="name">version</span>&gt;</span>4.3.20.RELEASE<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br></pre></td></tr></table></figure>
</li>
<li><p>在web.xml中配置SpringWeb上下文环境</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&lt;?xml version="1.0" encoding="UTF-8" ?&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">web-app</span> <span class="attr">version</span>=<span class="string">"3.0"</span></span></span><br><span class="line"><span class="tag">         <span class="attr">xmlns</span>=<span class="string">"http://java.sun.com/xml/ns/javaee"</span></span></span><br><span class="line"><span class="tag">         <span class="attr">xmlns:xsi</span>=<span class="string">"http://www.w3.org/2001/XMLSchema-instance"</span></span></span><br><span class="line"><span class="tag">         <span class="attr">xsi:schemaLocation</span>=<span class="string">"http://java.sun.com/xml/ns/javaee</span></span></span><br><span class="line"><span class="tag"><span class="string">                        http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="tag">&lt;<span class="name">servlet</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">servlet-name</span>&gt;</span>SpringServlet<span class="tag">&lt;/<span class="name">servlet-name</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">servlet-class</span>&gt;</span>org.springframework.web.servlet.DispatcherServlet<span class="tag">&lt;/<span class="name">servlet-class</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">init-param</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">param-name</span>&gt;</span>contextConfigLocation<span class="tag">&lt;/<span class="name">param-name</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">param-value</span>&gt;</span>classpath:spring.xml<span class="tag">&lt;/<span class="name">param-value</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;/<span class="name">init-param</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">servlet</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">servlet-mapping</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">servlet-name</span>&gt;</span>SpringServlet<span class="tag">&lt;/<span class="name">servlet-name</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">url-pattern</span>&gt;</span>/*<span class="tag">&lt;/<span class="name">url-pattern</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">servlet-mapping</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">web-app</span>&gt;</span></span><br></pre></td></tr></table></figure>

</li>
</ol>
<h4 id="request作用域"><a href="#request作用域" class="headerlink" title="request作用域"></a>request作用域</h4><blockquote>
<p>每次request请求，Spring都会创建一个单独的实例</p>
</blockquote>
<ol>
<li><p>编写Controller</p>
</li>
<li><p>配置request作用域，并将Controller交由SpringIOC管理</p>
<figure class="highlight routeros"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">&lt;bean <span class="attribute">class</span>=<span class="string">"com.aiolos.spring05.RequestController"</span> <span class="attribute">scope</span>=<span class="string">"request"</span>/&gt;</span><br></pre></td></tr></table></figure>
</li>
<li><p>运行结果<br><img src="/blog/images/20191113095816743.jpg" alt="运行结果"></p>
</li>
</ol>
<h4 id="session作用域"><a href="#session作用域" class="headerlink" title="session作用域"></a>session作用域</h4><blockquote>
<p>一次session请求，Spring只会实例化该Controller实例一次；<br>不同的session请求，都会实例化不同的实例</p>
</blockquote>
<ol>
<li><p>配置request作用域，并将Controller交由SpringIOC管理</p>
<figure class="highlight routeros"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">&lt;bean <span class="attribute">class</span>=<span class="string">"com.aiolos.spring05.SessionController"</span> <span class="attribute">scope</span>=<span class="string">"session"</span>/&gt;</span><br></pre></td></tr></table></figure>
</li>
<li><p>运行结果<br><img src="/blog/images/20191113100633764.jpg" alt="运行结果"></p>
</li>
</ol>
<h4 id="application作用域"><a href="#application作用域" class="headerlink" title="application作用域"></a>application作用域</h4><figure class="highlight routeros"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">&lt;bean <span class="attribute">class</span>=<span class="string">"com.aiolos.spring05.ApplicationController"</span> <span class="attribute">scope</span>=<span class="string">"application"</span>/&gt;</span><br></pre></td></tr></table></figure>

<h4 id="websocket作用域"><a href="#websocket作用域" class="headerlink" title="websocket作用域"></a>websocket作用域</h4><blockquote>
<p>使用场景非常少，视频略讲</p>
</blockquote>
<h4 id="总结-1"><a href="#总结-1" class="headerlink" title="总结"></a>总结</h4><p>request作用域：每次request请求，Spring都会创建一个单独的实例<br>session作用域：每个session请求，Spring都会创建一个单独的实例<br>application作用域：每个servletContext，Spring都会创建一个单独的实例<br>websocket作用域：每个websocket连接请求，Spring都会创建一个单独的实例</p>
<h3 id="自定义作用域"><a href="#自定义作用域" class="headerlink" title="自定义作用域"></a>自定义作用域</h3><p><strong>未学习</strong></p>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/blog/tags/Spring-IOC/" rel="tag"># Spring IOC</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/blog/2019/11/09/what-is-spring-AOP/" rel="next" title="Spring AOP">
                <i class="fa fa-chevron-left"></i> Spring AOP
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/blog/2019/11/10/what-is-spring-IOC-2/" rel="prev" title="Spring IOC二">
                Spring IOC二 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <p class="site-author-name" itemprop="name">aiolos</p>
              <p class="site-description motion-element" itemprop="description">Java Spring Hadoop 机器学习</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/blog/archives/">
              
                  <span class="site-state-item-count">126</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/blog/categories/index.html">
                  <span class="site-state-item-count">16</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/blog/tags/index.html">
                  <span class="site-state-item-count">33</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          

          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#JavaWeb发展史"><span class="nav-number">1.</span> <span class="nav-text">JavaWeb发展史</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#课程介绍"><span class="nav-number">2.</span> <span class="nav-text">课程介绍</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#课程内容"><span class="nav-number">2.1.</span> <span class="nav-text">课程内容</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#课程目标"><span class="nav-number">2.2.</span> <span class="nav-text">课程目标</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#什么是IOC"><span class="nav-number">3.</span> <span class="nav-text">什么是IOC</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#为什么要有IOC"><span class="nav-number">4.</span> <span class="nav-text">为什么要有IOC</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#没有IOC的日子"><span class="nav-number">4.1.</span> <span class="nav-text">没有IOC的日子</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Ioc是如何工作的"><span class="nav-number">5.</span> <span class="nav-text">Ioc是如何工作的</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#实现一个自己的Ioc容器————利用反射"><span class="nav-number">5.1.</span> <span class="nav-text">实现一个自己的Ioc容器————利用反射</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#使用SpringIoc容器管理Bean"><span class="nav-number">5.2.</span> <span class="nav-text">使用SpringIoc容器管理Bean</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#总结：使用SpringIOC管理Bean的三个步骤"><span class="nav-number">5.3.</span> <span class="nav-text">总结：使用SpringIOC管理Bean的三个步骤</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#使用Spring-IOC实例化Bean的三种方式"><span class="nav-number">6.</span> <span class="nav-text">使用Spring IOC实例化Bean的三种方式</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#通过默认构造方法实例化Bean"><span class="nav-number">6.1.</span> <span class="nav-text">通过默认构造方法实例化Bean</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#通过静态工厂方法实例化Bean"><span class="nav-number">6.2.</span> <span class="nav-text">通过静态工厂方法实例化Bean</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#通过实例工厂方法实例化Bean"><span class="nav-number">6.3.</span> <span class="nav-text">通过实例工厂方法实例化Bean</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#为Bean对象起别名的两种方式"><span class="nav-number">6.4.</span> <span class="nav-text">为Bean对象起别名的两种方式</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#总结"><span class="nav-number">6.5.</span> <span class="nav-text">总结</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#通过Spring-IOC注入Bean的属性值二种方法"><span class="nav-number">7.</span> <span class="nav-text">通过Spring IOC注入Bean的属性值二种方法</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#通过构造方法注入Bean的属性值"><span class="nav-number">7.1.</span> <span class="nav-text">通过构造方法注入Bean的属性值</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#通过set方法注入Bean的属性值"><span class="nav-number">7.2.</span> <span class="nav-text">通过set方法注入Bean的属性值</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#集合类型的属性值的注入"><span class="nav-number">7.2.1.</span> <span class="nav-text">集合类型的属性值的注入</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#null类型的属性值的注入"><span class="nav-number">7.2.2.</span> <span class="nav-text">null类型的属性值的注入</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#注入时创建内部Bean"><span class="nav-number">7.2.3.</span> <span class="nav-text">注入时创建内部Bean</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#构造方法和set方法注入属性值的简写形式——修改配置文件即可"><span class="nav-number">7.3.</span> <span class="nav-text">构造方法和set方法注入属性值的简写形式——修改配置文件即可</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Bean的作用域"><span class="nav-number">8.</span> <span class="nav-text">Bean的作用域</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#Singleton作用域-单例-——-Spring默认就是单例模式"><span class="nav-number">8.1.</span> <span class="nav-text">Singleton作用域(单例) —— Spring默认就是单例模式</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#prototype作用域-多例"><span class="nav-number">8.2.</span> <span class="nav-text">prototype作用域(多例)</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#单例-多例的组合作用域"><span class="nav-number">8.3.</span> <span class="nav-text">单例+多例的组合作用域</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#web环境作用域"><span class="nav-number">8.4.</span> <span class="nav-text">web环境作用域</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#request作用域"><span class="nav-number">8.4.1.</span> <span class="nav-text">request作用域</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#session作用域"><span class="nav-number">8.4.2.</span> <span class="nav-text">session作用域</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#application作用域"><span class="nav-number">8.4.3.</span> <span class="nav-text">application作用域</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#websocket作用域"><span class="nav-number">8.4.4.</span> <span class="nav-text">websocket作用域</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#总结-1"><span class="nav-number">8.4.5.</span> <span class="nav-text">总结</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#自定义作用域"><span class="nav-number">8.5.</span> <span class="nav-text">自定义作用域</span></a></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">aiolos</span>

  
</div>


  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Gemini</a> v5.1.4</div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/blog/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/blog/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/blog/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/blog/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/blog/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/blog/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/blog/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/blog/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/blog/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  

  

  

  

</body>
</html>
